package com.achievement.service.impl;

import com.achievement.domain.dto.PersonnelAcceptDTO;
import com.achievement.domain.entity.PersonnelAcceptEntity;
import com.achievement.domain.param.PersonnelAcceptParam;
import com.achievement.domain.vo.PersonnelAcceptVO;
import com.achievement.mapper.CFGCategoryMapper;
import com.achievement.mapper.PersonnelAcceptMapper;
import com.achievement.mappings.PersonnelAcceptMapping;
import com.achievement.service.IPersonnelAcceptService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.api.ApprovalApi;
import com.common.core.domain.AjaxResult;
import com.common.utils.DateUtils;
import com.common.utils.QueryWrapperUtils;
import com.common.utils.SecurityUtils;
import com.common.utils.bean.BizProcessMessages;
import com.flowable.domain.vo.task.BpmTaskApproveReqVO;
import com.flowable.service.IFlowTaskService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class PersonnelAcceptServiceImpl extends ServiceImpl<PersonnelAcceptMapper, PersonnelAcceptEntity> implements IPersonnelAcceptService {
    @Autowired
    private PersonnelAcceptMapping mapping;

    @Autowired
    private CFGCategoryMapper categoryMapper;

    //流程引擎
    @Autowired
    private IFlowTaskService flowTaskService;

    @Autowired
    private ApprovalApi approvalApi;

    private final static String module_name = "人员接受";

    @Override
    public void updateBusinessStatus(String tableName, String businessId, String checkStatus, String sysUserId) {
        if (com.common.utils.StringUtils.isEmpty(tableName) || com.common.utils.StringUtils.isEmpty(businessId) || com.common.utils.StringUtils.isEmpty(checkStatus))
            return;
        PersonnelAcceptEntity entity = new PersonnelAcceptEntity();
        entity.setId(businessId);
        entity.setCheckstatus(checkStatus);
        if ("2".equals(checkStatus)) {
            entity.setCheckdate(DateUtils.getTime());
            entity.setChecker(SecurityUtils.getNickName());
        }
        this.updateById(entity);
    }

    @Override
    public List<PersonnelAcceptVO> selectByPage(PersonnelAcceptParam param) {
        LambdaQueryWrapper<PersonnelAcceptEntity> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.like(StringUtils.isNotEmpty(param.getName()), PersonnelAcceptEntity::getName, param.getName());
        queryWrapper.like(StringUtils.isNotEmpty(param.getAcceptName()), PersonnelAcceptEntity::getAcceptName, param.getAcceptName());
        if (StringUtils.isNotEmpty(param.getUnitId())) {
            queryWrapper.in(PersonnelAcceptEntity::getUnitId, Arrays.asList(param.getUnitId().split(",")));
        }
        QueryWrapperUtils.applyChainWrapper(queryWrapper, param.getBeginDateStart(), param.getBeginDateEnd(), param.getBeginDateFormat(), "begin_date");
        QueryWrapperUtils.applyChainWrapper(queryWrapper, param.getEndDateStart(), param.getEndDateEnd(), param.getEndDateFormat(), "end_date");
        queryWrapper.eq(StringUtils.isNotEmpty(param.getResearchTypeId()), PersonnelAcceptEntity::getResearchTypeId, param.getResearchTypeId());
        //审核状态
        if (StringUtils.isNotEmpty(param.getCheckstatus())) {
            queryWrapper.in(PersonnelAcceptEntity::getCheckstatus, Arrays.asList(param.getCheckstatus().split(",")));
        }
        //左上角审核状态
        queryWrapper.eq(StringUtils.isNotEmpty(param.getLeftCheckstatus()), PersonnelAcceptEntity::getCheckstatus,
                param.getLeftCheckstatus());
        QueryWrapperUtils.getParams_achievement(queryWrapper, SecurityUtils.getLoginUser().getUser());

        queryWrapper.orderByDesc(PersonnelAcceptEntity::getCreateDate);
        List<PersonnelAcceptVO> voList = this.baseMapper.selectByPage(queryWrapper);
        Map<String, String> instanceTaskMap = approvalApi.getInstanceTaskMap(module_name);
        voList.stream().forEach(a -> {
            // 判断是否是审核人，并设置taskId
            String processInstanceId = a.getProcessInstanceId();
            if (com.common.utils.StringUtils.isNotEmpty(processInstanceId) && instanceTaskMap.containsKey(processInstanceId)) {
                a.setTaskId(instanceTaskMap.get(processInstanceId));
                a.setIsAuditor(true);
            } else {
                a.setIsAuditor(false);
            }
        });
        return voList;
    }

    /**
     * 左上方统计 通过，退回，待审核
     *
     * @param param
     */
    @Override
    public List<HashMap<String, Integer>> listStatistics(PersonnelAcceptParam param) {
        LambdaQueryWrapper<PersonnelAcceptEntity> queryWrapper = new LambdaQueryWrapper();
        List<PersonnelAcceptEntity> list = new ArrayList<>();
        queryWrapper.like(StringUtils.isNotEmpty(param.getName()), PersonnelAcceptEntity::getName, param.getName());
        queryWrapper.like(StringUtils.isNotEmpty(param.getAcceptName()), PersonnelAcceptEntity::getAcceptName, param.getAcceptName());
        if (StringUtils.isNotEmpty(param.getUnitId())) {
            queryWrapper.in(PersonnelAcceptEntity::getUnitId, Arrays.asList(param.getUnitId().split(",")));
        }
        QueryWrapperUtils.applyChainWrapper(queryWrapper, param.getBeginDateStart(), param.getBeginDateEnd(), param.getBeginDateFormat(), "begin_date");
        QueryWrapperUtils.applyChainWrapper(queryWrapper, param.getEndDateStart(), param.getEndDateEnd(), param.getEndDateFormat(), "end_date");
        queryWrapper.eq(StringUtils.isNotEmpty(param.getResearchTypeId()), PersonnelAcceptEntity::getResearchTypeId, param.getResearchTypeId());
        //审核状态
        if (StringUtils.isNotEmpty(param.getCheckstatus())) {
            queryWrapper.in(PersonnelAcceptEntity::getCheckstatus, Arrays.asList(param.getCheckstatus().split(",")));
        }
        //左上角审核状态
        queryWrapper.eq(StringUtils.isNotEmpty(param.getLeftCheckstatus()), PersonnelAcceptEntity::getCheckstatus,
                param.getLeftCheckstatus());
        QueryWrapperUtils.getParams_achievement(queryWrapper, SecurityUtils.getLoginUser().getUser());
        return this.baseMapper.listStatistics(queryWrapper);
    }

    @Override
    public List<PersonnelAcceptVO> getListByConditions(PersonnelAcceptParam param) {
        LambdaQueryWrapper<PersonnelAcceptEntity> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.like(StringUtils.isNotEmpty(param.getName()), PersonnelAcceptEntity::getName, param.getName());
        queryWrapper.like(StringUtils.isNotEmpty(param.getAcceptName()), PersonnelAcceptEntity::getAcceptName, param.getAcceptName());
        if (StringUtils.isNotEmpty(param.getUnitId())) {
            queryWrapper.in(PersonnelAcceptEntity::getUnitId, Arrays.asList(param.getUnitId().split(",")));
        }
        QueryWrapperUtils.applyChainWrapper(queryWrapper, param.getBeginDateStart(), param.getBeginDateEnd(), param.getBeginDateFormat(), "begin_date");
        QueryWrapperUtils.applyChainWrapper(queryWrapper, param.getEndDateStart(), param.getEndDateEnd(), param.getEndDateFormat(), "end_date");
        queryWrapper.eq(StringUtils.isNotEmpty(param.getResearchTypeId()), PersonnelAcceptEntity::getResearchTypeId, param.getResearchTypeId());
        //审核状态
        if (StringUtils.isNotEmpty(param.getCheckstatus())) {
            queryWrapper.in(PersonnelAcceptEntity::getCheckstatus, Arrays.asList(param.getCheckstatus().split(",")));
        }
        //左上角审核状态
        queryWrapper.eq(StringUtils.isNotEmpty(param.getLeftCheckstatus()), PersonnelAcceptEntity::getCheckstatus,
                param.getLeftCheckstatus());

        QueryWrapperUtils.getParams_achievement(queryWrapper, SecurityUtils.getLoginUser().getUser());

        queryWrapper.orderByDesc(PersonnelAcceptEntity::getCreateDate);
        List<PersonnelAcceptVO> voList = this.baseMapper.selectByPage(queryWrapper);

        voList = dealDict(voList);

        return voList;
    }

    @Override
    public PersonnelAcceptVO getInfoById(String id) {
        PersonnelAcceptEntity entity = this.getById(id);
        PersonnelAcceptVO PersonnelAcceptVO = mapping.entity2Vo(entity);

        //获取当前用户所有的代办列表
        Map<String, String> instanceTaskMap = approvalApi.getInstanceTaskMap(module_name);
        // 判断是否是审核人，并设置taskId
        String processInstanceId = PersonnelAcceptVO.getProcessInstanceId();
        if (StringUtils.isNotEmpty(processInstanceId) && instanceTaskMap.containsKey(processInstanceId)) {
            PersonnelAcceptVO.setTaskId(instanceTaskMap.get(processInstanceId));
            PersonnelAcceptVO.setIsAuditor(true);
        } else {
            PersonnelAcceptVO.setIsAuditor(false);
        }
        return PersonnelAcceptVO;
    }

    @Override
    public AjaxResult add(PersonnelAcceptDTO dto) {
        PersonnelAcceptEntity entity = mapping.dto2Entity(dto);
        Integer submitType = dto.getSubmitType();

        switch (submitType) {
            case 2: // 保存并通过
                entity.setProcessInstanceId("0");
                entity.setCheckstatus(String.valueOf(submitType));
                entity.setCheckdate(DateUtils.getTime());
                entity.setChecker(SecurityUtils.getNickName());
                break;
            case 1: // 提交
                entity.setCheckstatus(String.valueOf(submitType));
                if (!this.save(entity)) {
                    return AjaxResult.error(BizProcessMessages.SAVE_FAIL);
                }
                String processInstanceId = null;
                try {
                    //发起流程 业务状态由流程引擎更新
                    processInstanceId = approvalApi.businessEntryApproval(entity.getId(), module_name);
                } catch (Exception e) {
                    AjaxResult.error(BizProcessMessages.SAVE_PARTIAL_SUCCESS);
                }

                return StringUtils.isEmpty(processInstanceId)
                        ? AjaxResult.error(BizProcessMessages.SAVE_PARTIAL_SUCCESS)
                        : AjaxResult.success((Object)entity.getId());
            default: // 处理 -1（暂存）及其他情况
                entity.setCheckstatus(String.valueOf(submitType));
                break;
        }

        boolean r = this.save(entity);
        return r ? AjaxResult.success((Object)entity.getId()) : AjaxResult.error(BizProcessMessages.SAVE_FAIL);
    }


    @Override
    public AjaxResult update(PersonnelAcceptDTO dto) {
        PersonnelAcceptEntity entity = mapping.dto2Entity(dto);
        Integer submitType = dto.getSubmitType();

        switch (submitType) {
            case 2: // 保存并通过
                // 当前用户是否是审批人
                boolean isAuditor = dto.getIsAuditor();
                // 审批人直接审核（仅适用于提交类型2且为当前审核人的情况）
                if (isAuditor) {
                    if (this.updateById(entity)) {
                        BpmTaskApproveReqVO bta = new BpmTaskApproveReqVO();
                        bta.setId(dto.getTaskId());
                        bta.setReason("审核通过");
                        try {
                            flowTaskService.approveTask(SecurityUtils.getUserId(), bta);
                        } catch (Exception e) {
                            return AjaxResult.error(BizProcessMessages.SAVE_SUCCESS_APPROVE_FAIL, e.getMessage());
                        }

                        return AjaxResult.success(BizProcessMessages.SAVE_SUCCESS);
                    }
                    return AjaxResult.error(BizProcessMessages.SAVE_FAIL);
                }
                //处理非当前审批人保存并通过
                if (!dto.getCheckstatus().equals("2")){
                    entity.setProcessInstanceId("0");
                }
                entity.setCheckdate(DateUtils.getTime());
                entity.setChecker(SecurityUtils.getNickName());
                //只有管理员才会有非当前审核人的情况下有 "保存并提交"按钮,审核完后的结果只能是审核通过
                entity.setCheckstatus(String.valueOf(submitType));
                break;
            case 1:
                //暂存转提交
                if (!this.updateById(entity)) {
                    return AjaxResult.error(BizProcessMessages.SAVE_FAIL);
                }
                String returnProcessInstanceId = null;
                try {
                    returnProcessInstanceId = approvalApi.businessEntryApproval(entity.getId(), module_name);
                } catch (Exception e) {
                    return AjaxResult.error(BizProcessMessages.SAVE_PARTIAL_SUCCESS, e.getMessage());
                }

                return com.common.utils.StringUtils.isEmpty(returnProcessInstanceId)
                        ? AjaxResult.warn(BizProcessMessages.SAVE_PARTIAL_SUCCESS)
                        : AjaxResult.success(BizProcessMessages.SAVE_SUCCESS);
            case -1: // 暂存
                return this.updateById(entity)
                        ? AjaxResult.success(BizProcessMessages.SAVE_SUCCESS)
                        : AjaxResult.error(BizProcessMessages.SAVE_FAIL);
            default:
                break;
        }

        return this.updateById(entity)
                ? AjaxResult.success(BizProcessMessages.SAVE_SUCCESS)
                : AjaxResult.error(BizProcessMessages.SAVE_FAIL);
    }

    @Override
    public boolean batchRemove(List<String> ids) {
        boolean returnResult = false;
        returnResult = this.removeByIds(ids);
        return returnResult;
    }

    private List<PersonnelAcceptVO> dealDict(List<PersonnelAcceptVO> list) {
        List<Map<String, String>> unitList = categoryMapper.getAllUnitList();
        List<Map<String, String>> checkStateList = categoryMapper.getCheckStateList();
        list.stream().forEach(a -> {
            if (com.common.utils.StringUtils.isNotEmpty(a.getUnitId())) {
                Optional<Map<String, String>> optional = unitList.stream().filter(f -> f.get("id").equals(a.getUnitId())).findFirst();
                a.setUnitId(optional.isPresent() ? optional.get().get("name") : "");
            }
            if (com.common.utils.StringUtils.isNotEmpty(a.getCheckstatus())) {
                Optional<Map<String, String>> optional = checkStateList.stream().filter(f -> f.get("id").equals(a.getCheckstatus())).findFirst();
                a.setCheckstatus(optional.isPresent() ? optional.get().get("name") : "");
            }
        });
        return list;
    }
}
